﻿#include "FlameMage.h"
#include "../MapObject.h"
#include "../../../Shared/Enums.h"
#include "../../../Shared/Functions/Functions.h"

using namespace Server::MirDatabase;
namespace S = ServerPackets;

namespace Server::MirObjects::Monsters
{

    FlameMage::FlameMage(MonsterInfo *info) : RightGuard(info)
    {
    }

    void FlameMage::CompleteRangeAttack(std::vector<std::any> &data)
    {
        MapObject *target = std::any_cast<MapObject*>(data[0]);
        int damage = std::any_cast<int>(data[1]);
        DefenceType defence = std::any_cast<DefenceType>(data[2]);

        if (target == nullptr || !target->IsAttackTarget(this) || target->getCurrentMap() != getCurrentMap() || target->Node == nullptr)
        {
            return;
        }

        std::vector<MapObject*> targets = FindAllTargets(2, target->getCurrentLocation());

        if (targets.empty())
        {
            return;
        }

        for (int i = 0; i < targets.size(); i++)
        {
            targets[i]->Attacked(this, damage, defence);
        }
    }

    void FlameMage::ProcessTarget()
    {
        if (getTarget() == nullptr || !getCanAttack())
        {
            return;
        }

        if (InAttackRange() && getEnvir()->getTime() < FearTime)
        {
            Attack();
            return;
        }

        FearTime = getEnvir()->getTime() + 5000;

        if (getEnvir()->getTime() < ShockTime)
        {
            setTarget(nullptr);
            return;
        }

        int dist = Functions::MaxDistance(getCurrentLocation(), getTarget()->getCurrentLocation());

        if (dist >= getAttackRange())
        {
            MoveTo(getTarget()->getCurrentLocation());
        }
        else
        {
            MirDirection dir = Functions::DirectionFromPoint(getTarget()->getCurrentLocation(), getCurrentLocation());

            if (Walk(dir))
            {
                return;
            }

            switch (getEnvir()->Random->Next(2)) //No favour
            {
                case 0:
                    for (int i = 0; i < 7; i++)
                    {
                        dir = Functions::NextDir(dir);

                        if (Walk(dir))
                        {
                            return;
                        }
                    }
                    break;
                default:
                    for (int i = 0; i < 7; i++)
                    {
                        dir = Functions::PreviousDir(dir);

                        if (Walk(dir))
                        {
                            return;
                        }
                    }
                    break;
            }

        }
    }
}
